<?php

namespace Admin\Controller;

use Think\Controller;

class IndexController extends Controller
{
    public function index()
    {
        if (!$_POST) {
            if (!checkCookie()) {
                redirect(U('Admin/Index/login'));
            }
            $this->display('index');
        }
    }

    public function pass()
    {
        if (!IS_POST) {
            if (!checkCookie()) {
                $this->redirect('Admin/Index/login');
            }
            $this->display();
        } else {
            $adminmodel = M('admin');
            $mpass = I('post.mpass');
            $newpass = I('post.newpass');
            $password = $adminmodel->find(1);
            if (md5($mpass . $password['salt']) != $password['password']) {
                $this->error('原始密码错误');
            }
            $user['password'] = md5($newpass . $password['salt']);
            if ($adminmodel->where('adminid', 1)->save($user)) {
                $this->success('修改成功');
            } else {
                $this->error("修改失败:原密码重复/其他原因起联系管理员");
            }
        }
    }

    public function login()
    {
        if (!IS_POST) {
            echo "<script>if(self!=top) top.location=self.location;</script>";
            $this->assign('waitSecond', '1');
            $this->display();
        } else {
            $username = I('post.username');
            $password = I('post.password');
            $username = trim($username);
            $password = trim($password);
            if (!$username || !$password) {
                $this->error('请填写账号或密码');
            }
            $user = M('admin')->where(array('username' => $username))->select()[0];
            if (!$user) {
                $this->error('账号不存在');
            } elseif (md5($password . $user['salt']) != $user['password']) {
                $this->error('密码错误');
            } else {
                cookie('username', $user['name'], 3600);
                cookie('code', md5($user['name'] . 'admin123'), 3600);
                $this->success("登录成功", (U('Admin/Index/index')));
            }
        }
    }

    public function logout()
    {
        // 清除所有session
        cookie('username', null);
        cookie('code', null);
        redirect(U('Admin/Index/login'));
    }

}